exports.up = function (knex, Promise) {
	return Promise.resolve()
    .then(() =>  knex.schema.createTable('stock', (t) => {
        t.increments();

        t.string('name', 32).unique();

        t.string('code', 16).unique();

        t.string('shortcut', 16);	//	四位快捷键

        t.string('summary');
    }))
    .then(() =>  knex.schema.createTable('user_stock', (t) => {
        t.increments();

        t.bigInteger('user_id')
            .references('id')
            .inTable('user').notNullable();

        t.bigInteger('stock_id')
            .references('id')
            .inTable('stock').notNullable();

        t.integer('status').unsigned().defaultTo(0);   //   bought status, 0: idle, 1: bought, 2: inhand  

        t.decimal('price', 10);

        t.timestamps();
    }))
    .then(() =>  knex.schema.createTable('note', (t) => {
        t.increments();

        t.bigInteger('user_stock_id')
            .references('id')
            .inTable('user_stock').notNullable();

        t.string('body');

        t.integer('type').unsigned().defaultTo(0);   //    0: write, 1: changeTime, 2: buy, 3: sell, etc  

        //t.timestamp('created_at').defaultTo(knex.fn.now());
        t.timestamps();
    }))
    .then(() =>  knex.schema.createTable('user_tag', (t) => {
        t.increments();

        t.bigInteger('user_id')
            .references('id')
            .inTable('user').notNullable();

        t.string('title');
    }))
    .then(() =>  knex.schema.createTable('user_stocks_tag', (t) => {
        t.increments();

        t.bigInteger('user_tag_id')
            .references('id')
            .inTable('user_tag').notNullable();

        t.bigInteger('user_stock_id')
            .references('id')
            .inTable('user_stock').notNullable();
    }))
    .then(() =>  knex.schema.createTable('price_log', (t) => {
        t.increments();

        t.bigInteger('user_stock_id')
            .references('id')
            .inTable('user_stock').notNullable();

        t.decimal('price', 10);

        t.timestamp('created_at').defaultTo(knex.fn.now());
    }))
};

exports.down = function (knex, Promise) {
    return Promise.resolve()
    .then(() => knex.schema.dropTableIfExists('stock'))
    .then(() => knex.schema.dropTableIfExists('user_stock'))
    .then(() => knex.schema.dropTableIfExists('note'))
    .then(() => knex.schema.dropTableIfExists('user_tag'))
    .then(() => knex.schema.dropTableIfExists('user_stocks_tag'))
    .then(() => knex.schema.dropTableIfExists('price_log'))
};